<template>
  <div v-loading="loading" class="analysisContainer h-flex">
    <div class="h-flex-elastic" style="overflow: hidden;">
      <div class="analysisPictureContainer">
        <div class="h-flex work-info">
          <span>起始站：{{ startSiteName }}，终止站：{{ endSiteName }}，上传时间：{{ dateVal }}</span>
          <div class="buttonsLinks">
            <el-button type="primary" size="mini" class="form-button" icon="el-icon-link">横向对比</el-button>
            <el-button type="primary" size="mini" class="form-button" icon="el-icon-link" @click="toDefectTransverse">纵向对比</el-button>
            <el-button type="primary" size="mini" class="form-button" icon="el-icon-link" @click="toRelation()">缺陷关联分析</el-button>
          </div>
        </div>
        <div class="analysisPicturyInnform">
          <pillar-query-list v-if="showPillarPager" :pillar-pager="pillarPager" :detect-job-id="detectJobIdNew" :pillar-tabs-parent="pillarTabs" @setDeviceCode="setDeviceCode" />
          <div class="pictureWrapper" style="height: calc(100% - 80px);">
            <div style="width:384px;height: calc(100% - 85px); border-right:1px solid #E4E7ED">
              <el-tabs v-model="picTabActive" type="card" class="tabstyle" @keydown.native.capture.stop.prevent>
                <el-tab-pane label="全部" name="0">
                  <div v-show="listAll.length === 0" class="no-img">暂无图片</div>
                  <device4c-content ref="content0" :list="listAll" :revese="revese" @changeimg="changeImg" />
                </el-tab-pane>
                <el-tab-pane v-for="(item,index) in tabList" :key="index" :label="item" :name="`${index+1}`">
                  <div v-show="listType[`${index+1}`].length === 0" class="no-img">暂无图片</div>
                  <device4c-content :ref="`content${index+1}`" :list="listType[`${index+1}`]" :revese="revese" @changeimg="changeImg" />
                </el-tab-pane>
              </el-tabs>
              <div class="direction">
                <el-button :class="{active: revese==='all'}" size="mini" @click="revese = 'all'">全部</el-button>
                <el-button :class="{active: revese===1}" size="mini" @click="revese = 1">正面相机</el-button>
                <el-button :class="{active: revese===0}" size="mini" @click="revese = 0">反面相机</el-button>
              <!-- <el-button :class="{active: revese===2}" size="mini" @click="revese = 2">其他相机</el-button> -->
              </div>
            </div>
            <div class="imgshow">
              <div v-show="imgContent.length" class="imgshow-title">位置：{{ positionname }}&nbsp;隧道：{{ getTunnel(tunnel) }}&nbsp;&nbsp;公里标：{{ formatData(imgContent[1]) }}
                &nbsp;&nbsp;&nbsp;&nbsp;杆号：{{ imgContent[2] }}&nbsp;&nbsp;&nbsp;&nbsp;相机编号：{{ checkReversenum||imgContent[4] }}&nbsp;&nbsp;&nbsp;&nbsp;相机名称：{{ getcameraName(imgContent[4]) }}
                <el-button class="img-buttom" @click="changeStr()">正面</el-button>
                <el-button class="img-buttom img-buttomnext" @click="changeStr(1)">反面</el-button>
              </div>
              <a4c-imgs v-if="isShowImg" :picpath="imgPath" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Device4cContent from './A4cContentCopy'
import A4cImgs from './A4cImgsCopy'
import PillarQueryList from './PillarList'
import { getC4ImageBySiteIdAndPillarId, getC4IndexSiteListByDetectJobId, getC4IndexPillarListByDetectJobIdAndSiteId } from '@/api/cms/detect-data'
var CameraPosConfig1 = require('./CameraPosConfig_光芒.xml')
var CameraPosConfig2 = require('./CameraPosConfig_唐源 _怀化.xml')
export default {
  name: 'Analysis4C',
  components: {
    Device4cContent,
    PillarQueryList,
    A4cImgs
  },
  props: {
    showPillarPager: {
      type: Boolean,
      default: false
    },
    detectJobId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      checkReversenum: null,
      xmlList: [], // 获取的xml数据
      positionname: null,
      tunnel: null,
      imgContent: [],
      isShowImg: true,
      tabList: ['支持装置', '接触悬挂', '附加悬挂', '吊柱座', '其他（杆号）'],
      loading: false,
      revese: 1, // 正反向图片
      picTabActive: '0', // 当前类型tab
      listAll: [], // 存放所有图片列表
      // 杆号、支柱等类型区分
      listType: {
        '1': [],
        '2': [],
        '3': [],
        '4': [],
        '5': []
      },
      pillarPager: [], // 存放支柱列表
      pillarTabs: [],
      dateVal: '',
      pillarImageList: {},
      detectJobIdNew: '',
      imgPath: '',
      // 存放的是所以类型下当前展示的图片
      picPath: {
        '0': {},
        '1': {},
        '2': {},
        '3': {},
        '4': {},
        '5': {}
      },
      endSiteName: '',
      startSiteName: ''

    }
  },
  watch: {
    // 监听正反相机切换，改变图片展示
    revese() {
      this.picPath = {
        '0': {},
        '1': {},
        '2': {},
        '3': {},
        '4': {},
        '5': {}
      }
      this.tabchangge()
    },
    // 监听tab类型改变事件
    picTabActive(val) {
      if (this.picPath[val].filePath) {
        this.changeImg(this.picPath[val])
      } else {
        this.tabchangge()
      }
    },
    // 监听传过来的列表id，通过接口获取此次检测的数据，包括区间和支柱
    detectJobId(val) {
      const queryParams = {}
      const detectJobId = val.split('_')[0]
      const startName = val.split('_')[1]
      const endName = val.split('_')[2]
      const date = val.split('_')[3]
      // if (xmltype === '1') {
      //   this.xmlList = CameraPosConfig1.CameraPosConfig.AreaTypeList[0].TypeInfo
      // } else {
      //   this.xmlList = CameraPosConfig2.CameraPosConfig.AreaTypeList[0].TypeInfo
      // }
      this.dateVal = date
      this.startSiteName = startName
      this.endSiteName = endName
      queryParams.detectJobId = detectJobId
      this.detectJobIdNew = detectJobId
      var that = this
      this.loading = true
      this.showPillarPager && getC4IndexSiteListByDetectJobId(queryParams).then(response => {
        this.loading = false
        console.log('通过锚段查询支柱信息及区间站场名称', response)
        that.pillarPager = response.data || []
        that.getC4IndexPillarListNum(detectJobId)
        that.positionname = that.pillarPager[0].siteName
      }).catch(_ => {
        this.loading = false
      })
    }
  },
  mounted() {
    window.addEventListener('keyup', this.handleKeyup)
  },
  methods: {
    getC4IndexPillarListNum(val) {
      getC4IndexPillarListByDetectJobIdAndSiteId({ detectJobId: val, siteId: this.pillarPager[0].siteId }).then(res => {
        this.pillarTabs = res.data
      })
    },
    getTunnel(val) {
      if (!val || !val.toString().replace(/[^\u4e00-\u9fa5]/gi, '')) return '无隧道'
      return val.toString().replace(/[^\u4e00-\u9fa5]/gi, '')
    },
    // 格式化公里标
    formatData(data) {
      if (!data) return ''
      return data.toString().substr(0, 5) + '+' + data.toString().substr(5, 3) + '.00'
    },
    // 获取相机名称
    getcameraName(num) {
      if (!this.xmlList.length || !num) return ''
      for (const item of this.xmlList) {
        if (item.$.CameraNo === num) {
          return item.$.Name
        }
      }
      return ''
    },
    // 获取当前照片基本信息
    getimgContent(item) {
      if (!item.fileName) {
        this.imgContent = []
        return
      }
      // var dd = item.filePath.split('/').pop()
      var ss = item.fileName.split('_')
      var val = ss[ss.length - 1]
      ss[ss.length - 1] = val.substring(0, val.length - 4)
      this.imgContent = ss
    },
    // 键盘事件
    handleKeyup(event) {
      if (event.key === 'ArrowDown') {
        if (this.picTabActive === '0') {
          this.$refs[`content${this.picTabActive}`].add4()
        } else {
          this.$refs[`content${this.picTabActive}`][0].add4()
        }
      } else if (event.key === 'ArrowUp') {
        if (this.picTabActive === '0') {
          this.$refs[`content${this.picTabActive}`].reduce4()
        } else {
          this.$refs[`content${this.picTabActive}`][0].reduce4()
        }
      } else if (event.key === 'ArrowRight') {
        if (this.picTabActive === '0') {
          this.$refs[`content${this.picTabActive}`].add()
        } else {
          this.$refs[`content${this.picTabActive}`][0].add()
        }
      } else if (event.key === 'ArrowLeft') {
        if (this.picTabActive === '0') {
          this.$refs[`content${this.picTabActive}`].reduce()
        } else {
          this.$refs[`content${this.picTabActive}`][0].reduce()
        }
      }
    },
    tabchangge() {
      if (this.picTabActive === '0') {
        this.picPath[this.picTabActive] = this.listAll[0] || {}
      } else {
        this.picPath[this.picTabActive] = this.listType[this.picTabActive][0] || {}
      }
      this.changeImg(this.picPath[this.picTabActive])
    },
    // 切换单张照片正反
    changeStr(istrue) {
      const str = this.picPath[this.picTabActive].picPath
      this.imgPath = this.picPath[this.picTabActive].picPath
      if (this.picPath[this.picTabActive].cameraSide) {
        if (istrue) {
          this.isShowImg = false
          this.imgContent[4] = this.picPath[this.picTabActive].Reverse
          this.checkReversenum = this.picPath[this.picTabActive].Reverse
          this.imgPath = str.substr(0, str.length - 6) + this.picPath[this.picTabActive].Reverse + str.substr(str.length - 4, str.length)
        } else {
          this.imgContent[4] = this.picPath[this.picTabActive].CameraNo
          this.checkReversenum = null
        }
      } else {
        if (!istrue) {
          this.isShowImg = false
          this.checkReversenum = this.picPath[this.picTabActive].CameraNo
          this.imgContent[4] = this.picPath[this.picTabActive].CameraNo
          this.imgPath = str.substr(0, str.length - 6) + this.picPath[this.picTabActive].CameraNo + str.substr(str.length - 4, str.length)
        } else {
          this.checkReversenum = null
          this.imgContent[4] = this.picPath[this.picTabActive].Reverse
        }
      }

      this.$nextTick(_ => {
        this.isShowImg = true
      })
    },
    // 切换图片
    changeImg(url) {
      this.getimgContent(url)
      this.picPath[this.picTabActive] = url.filePath ? url : { filePath: '' }
      this.checkReversenum = null
      this.imgPath = this.picPath[this.picTabActive].filePath
      this.isShowImg = false
      this.$nextTick(_ => {
        this.isShowImg = true
      })
    },
    // 根据xml判断获取的图片正反类型
    xmlTypeList(data) {
      var that = this
      data && data.forEach(item => {
        if (item.fileName) {
          const ss = item.fileName.split('_')
          const num = ss[ss.length - 1].substring(0, ss[ss.length - 1].length - 4)
          that.xmlList.forEach(child => {
            if (child.$.CameraNo === num) {
              if (child.$.Name.indexOf('(正)') !== -1) {
                item.cameraSide = 1
                item.CameraNo = child.$.CameraNo
                item.Reverse = child.$.Reverse
              } else {
                item.cameraSide = 0
                item.CameraNo = child.$.Reverse
                item.Reverse = child.$.CameraNo
              }
            }
          })
        }
      })
    },
    // 获取支柱图片列表
    getImages(detectJobId, siteId, pillarId) {
      this.picTabActive = '0'
      this.loading = true
      this.listAll = []
      this.revese = 1
      const queryParams = {}
      queryParams.detectJobId = detectJobId
      queryParams.pillarId = pillarId
      queryParams.siteId = siteId
      var that = this
      if (queryParams.detectDate !== '') {
        this.picPath = {
          '0': {},
          '1': {},
          '2': {},
          '3': {},
          '4': {},
          '5': {}
        }
        getC4ImageBySiteIdAndPillarId(queryParams).then(response => {
          this.loading = false
          // 4c图片
          console.log('4c图片', response)
          // 根据xml重置图片正反
          // this.xmlTypeList(response.data)
          that.listAll = response.data || []
          const byType = {}
          response.data && response.data.forEach(item => {
            if (!byType[item.pictureType]) {
              byType[item.pictureType] = []
            }
            byType[item.pictureType].push(item)
          })
          that.listType = Object.assign({ '1': [], '2': [], '3': [], '4': [], '5': [] }, byType)
          this.changeImg(this.listAll[0])
        })
      } else {
        this.loading = false
        this.listAll = []
      }
    },
    setDeviceCode(val, name, tunnel, pillarId) {
      if (name) {
        this.positionname = name
      }
      if (tunnel) {
        this.tunnel = tunnel
      }
      this.getImages(this.detectJobIdNew, val, pillarId)
      this.$emit('regetTimeAxis', val, '4C')
    },
    toRelation() {
      this.$router.push(
        '/cms/comprehensive-analysis/defect-relation'
      )
    },
    toDefectTransverse() {
      this.$router.push(
        '/cms/comprehensive-analysis/defect-transverse'
      )
    }
  }
}
</script>

<style lang="scss" scoped>
  .analysisContainer {
    height: 100%;
    color: #fff;
    background: #F1F4FB;

    .analysisPictureContainer {
      position: relative;
      z-index: 1;
      height: 100%;
      padding: 0;
      .work-info{
        height: 50px;
        color: #000;
        justify-content: space-between;
        align-items: center;
        font-size: 16px;
        padding: 0 20px;
      }
      .analysisPicturyInnform{
        height: calc(100% - 80px);
        background: #fff;
        margin: 15px;
        box-shadow: 0 0 20px 5px rgba(0,47,138,0.04);
        border-radius: 10px;
        overflow: hidden;
        padding:20px;
        margin-top: 0;
      }
      .pictureWrapper {
        position: relative;
        z-index: 1;
        display: flex;
        height: 100%;
        .tabstyle{
          height: 100%;
          .el-tab-pane{
            height: 100%;
          }
         ::v-deep .el-tabs__header{
            margin: 0 0 5px 0;
          }
          ::v-deep .el-tabs__content{
            height: 100%;
          }
        }
        .imgshow{
          flex:1;
          overflow: hidden;
          position: relative;
          .imgshow-title{
            position: absolute;
            z-index: 100;
            top: 0;
            color: white;
            font-size: 14px;
            height: 28px;
            line-height: 28px;
            width: 100%;
            padding-left: 10px;
            opacity: 0.7;
            background: #818181;
          }
        }
      }

      .direction {
        display: flex;
        width: 384px;
        background:white;
        height: 42px;
        position: absolute;
        bottom:0;
        left: 0;
        z-index: 5;

        .el-button {
          flex: 1;
          float: left;
          margin: 0 !important;
          border-radius: 0;

          &:nth-child(n+2) {
            border-left: 0;
          }

          &.active {
            background: white;
            color: #409eff;
          }
        }
      }
    }

    .pillar-query-list {
      height: 80px;
    }

    .pillar-query-list + .el-container {
      height: calc(100% - 80px);
    }

    .no-img {
      line-height: 50px;
      color: #666;
      text-align: center;
    }
  }

  .el-tabs {
    ::v-deep .el-tabs__item {
      color: black;

      &.is-active {
        color: #409eff;
      }
    }
  }
  .img-buttom{
    position: absolute;
    right: 52px;
    height: 28px;
    line-height: 28px;
    padding: 0 10px;
    border-radius: 0;
  }
  .img-buttomnext{
    right: 0;
  }
</style>
